import 'dart:async';
import 'dart:convert';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:interview_flutter/manager/InterviewConfig.dart';
import 'package:interview_flutter/utils/KLog.dart';
import 'package:vibration/vibration.dart';

import '../../../hydra/service/rtc_sdk_service.dart';
import '../../../model/interview/interview_detail_model.dart';
import '../../../model/interview/voice_call_info.dart';
import '../../../pages/interview/dialog/call_error_dialog.dart';

final interviewDetailProvider = StateNotifierProvider.autoDispose<InterviewDetailNotifier, InterviewDetailModel>((ref) {
  KLog.i("RtcSdkService", "Provider CREATED");
  final rtcService = ref.read(rtcSdkServiceProvider); // 获取 RtcSdkService 实例
  final notifier = InterviewDetailNotifier(ref);

  // 监听 RTC 消息事件
  final roomEventSub = rtcService.onRoomMessageReceived.listen((event) {
    if (notifier.mounted) {
      // 确保 Notifier 仍然挂载
      notifier._handleRtcRoomMessage(event);
    }
  });

  //监听 RTC 错误事件 (可选, 如果错误也影响 InterviewDetailModel)
  final errorEventSub = rtcService.onErrorOccurred.listen((event) {
    if (notifier.mounted) {
      notifier._handleRtcError(event);
    }
  });

  final ieltsCardTextSub = rtcService.onIeltsCardTextReceived.listen((event) {
    if (notifier.mounted) {
      notifier._handleRtcIeltsCardText(event);
    }
  });

  ref.onDispose(() {
    KLog.i("RtcSdkService", "Provider DISPOSED. Cancelling subscriptions.");
    roomEventSub.cancel();
    errorEventSub.cancel();
    ieltsCardTextSub.cancel();
  });

  return notifier;
});

class InterviewDetailNotifier extends StateNotifier<InterviewDetailModel> {
  //结束语
  final interviewerEndForJob = "祝你在后续的职业发展中一切顺利";
  final interviewerEndForIelts = "scoring your performance across all the assessment criteria";
  final showCardMsgForIelts = "here is your topic";

  final StateNotifierProviderRef _ref; // 用于读取其他 providers 或 rtcService (如果需要再次读取)
  late final RtcSdkService _rtcService; // 持有 RtcSdkService 实例以便调用其方法

  // Notifier 内部维护 AI 是否刚说完一句话的状态，用于决定何时调用 startAiStreaming
  bool _aiJustFinishedLastSentenceNotifier = true;

  //是否显示字幕
  bool isShowSubtitle = true;
  InterviewType interviewType = InterviewType.job;
  String roomId = "";
  String taskId = "";

  int seconds = 0;
  Timer? _pageTimer;
  Timer? _bottomBarDebounceTimer;
  Timer? _showCardTimer;
  Timer? _finishInterviewTimer;

  InterviewDetailNotifier(this._ref) : super(InterviewDetailModel.empty()) {
    _rtcService = _ref.read(rtcSdkServiceProvider);
    KLog.i("RtcSdkService", "CONSTRUCTOR called, initial state: ${state.msgList.isEmpty}");
    _initRTCRoom();
  }

  Future<void> _initRTCRoom() async {
    interviewType = InterviewConfig.instance.interviewType;
    isShowSubtitle = InterviewConfig.instance.isShowSubtitle;
    print('_initRTCRoom== isShowSubtitle=$isShowSubtitle');
    final jsonStr = await RtcSdkService.createRTCRoom();
    VoiceCallInfo? voiceCallInfo;
    try {
      final jsonMap = jsonDecode(jsonStr) as Map<String, dynamic>;
      voiceCallInfo = VoiceCallInfo.fromJson(jsonMap);
    } catch (e) {
      print('解析 JSON 失败: $e');
    }
    if (voiceCallInfo == null) {
      return;
    }
    InterviewConfig.instance.setUpRealResUrl(voiceCallInfo.interviewer);
    roomId = voiceCallInfo.roomId ?? '';
    taskId = voiceCallInfo.taskId ?? '';
    KLog.i("RtcSdkService", '创建房间 roomId=$roomId taskId=$taskId');
    final isCreateRTCRoomSuccess = roomId.isEmpty ? false : true;
    state = state.copyWith(isCreateRTCRoomSuccess: isCreateRTCRoomSuccess);
    if (isCreateRTCRoomSuccess) {
      _pageTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        seconds++; // 每秒递增
      });
    }
  }

  @override
  void dispose() {
    _pageTimer?.cancel();
    _bottomBarDebounceTimer?.cancel();
    _showCardTimer?.cancel();
    _finishInterviewTimer?.cancel();
    super.dispose();
  }

  void publishStream() {
    _rtcService.publishStream();
  }

  // 检查设备是否支持震动
  Future<bool> _hasVibrationSupport() async {
    bool? hasVibrator = await Vibration.hasVibrator();
    return hasVibrator ?? false;
  }

  // 触发简单震动
  void _vibrate() async {
    if (await _hasVibrationSupport()) {
      Vibration.vibrate(duration: 100); // 震动500毫秒
    } else {
      print("设备不支持震动");
    }
  }

  // 处理来自 RtcSdkService 的房间消息事件
  // ai 说话，正在说话：隐藏 BottomBar，重置 AnswerBtn，说完 显示 BottomBar，
  // 我说，更新 AnswerBtn
  //有任务卡，隐藏 BottomBar
  void _handleRtcRoomMessage(RtcRoomMessageEvent event) {
    final isAISpeedSay = event.isAISpeedSay;
    final msg = event.msg;
    final definite = event.definite;
    final onUserSpeakState = event.onUserSpeakState;
    if (onUserSpeakState) {
      _rtcService.unpublishStream();
      state = state.copyWith(isInterruptInterview: true);
      return;
    }
    if (isAISpeedSay) {
      _bottomBarDebounceTimer?.cancel();
      if (!isShowSubtitle) {
        if (definite) {
          _aiJustFinishedLastSentenceNotifier = true;
          if (!msg.contains(showCardMsgForIelts)) {
            _bottomBarDebounceTimer = Timer(const Duration(milliseconds: 1000), () {
              _vibrate();
              updateBottomBarVisible(true); // 延时显示 bottom bar
              setAiDefiniteState(true);
              setAiSpeakingState(false);
            });
          } else {
            _rtcService.unpublishStream();
            _showCardTimer?.cancel();
            _showCardTimer = Timer(const Duration(milliseconds: 1000), () {
              state = state.copyWith(showCardMsg: true);
              updateBottomBarVisible(false); // 延时显示 bottom bar
              setAiDefiniteState(true);
              setAiSpeakingState(false);
            });
          }
          if (msg.contains(interviewerEndForJob) || msg.contains(interviewerEndForIelts)) {
            _rtcService.unpublishStream();
            _finishInterviewTimer?.cancel();
            _finishInterviewTimer = Timer(const Duration(milliseconds: 3000), () {
              state = state.copyWith(isFinishInterview: true);
            });
          }
        } else {
          setAiDefiniteState(false);
          setAiSpeakingState(true);
        }
      } else {
        // AI 正在说话
        if (_aiJustFinishedLastSentenceNotifier) {
          startAiStreaming(); // 这个方法会添加空消息并设置 _isStreamingAiMessage = true
          _aiJustFinishedLastSentenceNotifier = false;
        }
        if (definite) {
          //防抖
          if (!msg.contains(showCardMsgForIelts)) {
            _bottomBarDebounceTimer = Timer(const Duration(milliseconds: 1000), () {
              _vibrate();
              updateBottomBarVisible(true);
              setAiDefiniteState(true);
              setAiSpeakingState(false);
            });
          } else {
            _rtcService.unpublishStream();
            _showCardTimer?.cancel();
            _showCardTimer = Timer(const Duration(milliseconds: 1000), () {
              state = state.copyWith(showCardMsg: true);
              updateBottomBarVisible(false); // 延时显示 bottom bar
              setAiDefiniteState(true);
              setAiSpeakingState(false);
            });
          }
        } else {
          updateBottomBarVisible(false);
          setAiDefiniteState(false);
          setAiSpeakingState(true);
        }
        // 更新流式文本
        updateAiStreamingText(msg);
        if (definite) {
          // AI 这句话说完了
          finalizeAiStreamingMessage(); // 这个方法会固化消息并设置 _isStreamingAiMessage = false
          _aiJustFinishedLastSentenceNotifier = true;

          if (msg.contains(interviewerEndForJob) || msg.contains(interviewerEndForIelts)) {
            _rtcService.unpublishStream();
            _finishInterviewTimer?.cancel();
            _finishInterviewTimer = Timer(const Duration(milliseconds: 3000), () {
              state = state.copyWith(isFinishInterview: true);
            });
          }
        } else {
          updateAnswerBtnVisible(false);
        }
      }
    } else {
      setAiDefiniteState(definite);
      setAiSpeakingState(false);
      if (state.showCardMsg) {
        updateBottomBarVisible(false);
        return;
      }
      updateBottomBarVisible(true);
      updateAnswerBtnVisible(true);
      // AI 没有在说话 (isAISpeedSay == false)
      _aiJustFinishedLastSentenceNotifier = true; // AI 没在说话，等同于“刚结束”（为下次开始做准备）
      if (msg.isNotEmpty) {
        updateCandidateTextText(msg);
      }
    }
  }

  void resetFinishInterview() {
    state = state.copyWith(isFinishInterview: false);
  }

  void resetInterruptInterview() {
    state = state.copyWith(isInterruptInterview: false);
  }

  void resetShowCardMsg() {
    _vibrate();
    state = state.copyWith(showCardMsg: false);
    updateBottomBarVisible(true);
  }

  void _handleRtcError(RtcErrorEvent event) {
    _ref.read(callErrorDialogProvider.notifier).state = CallErrorDialogInfo();
  }

  void _handleRtcIeltsCardText(RtcIeltsCardTextEvent event) {
    state = state.copyWith(ieltsCardText: event.ieltsCardText);
  }

  Future<void> userFinishedAnswering() async {
    if (!mounted) return;
    final messageToSend = state.candidateText;
    if (messageToSend.trim().isEmpty) {
      return;
    }
    addUserMessage(messageToSend);
    clearCandidateText();
    updateBottomBarVisible(false);
    _aiJustFinishedLastSentenceNotifier = true;
    await _rtcService.sendFinishRecognitionMessage();
  }

  Future<void> leaveRoom({bool isRollback = false}) async {
    await _rtcService.leaveRoom(isRollback);
    _aiJustFinishedLastSentenceNotifier = true;
  }

  // 内部标志，表示当前是否正在处理一个AI的流式消息
  // true: AI正在说话，interviewerText是流式内容，msgList中应该有一个空AI消息等待填充
  // false: AI当前没有在流式说话
  bool _isStreamingAiMessage = false;

  void _addMessage(MessageModel newMessage) {
    final currentMessages = state.msgList;
    final updatedMsgList = List<MessageModel>.from(currentMessages)..add(newMessage);
    state = state.copyWith(msgList: updatedMsgList);
  }

  // 公开的添加消息方法，用于用户发送消息或系统添加完整的非流式AI消息
  void addUserMessage(String text) {
    // 如果用户发消息时，AI正在流式输出，则先固化AI的消息
    if (_isStreamingAiMessage) {
      _finalizeStreamingAiMessage();
    }
    _addMessage(MessageModel(text: text, sender: MessageSender.candidate, timestamp: DateTime.now()));
    // 通常用户发消息后，AI的流式状态也应重置（如果之前没重置）
    _isStreamingAiMessage = false;
    state = state.copyWith(interviewerText: ""); // 确保清空
  }

  // AI 开始流式输出 (通常在收到 isAISpeedSay=true 且是新话语的第一个片段时调用)
  void startAiStreaming() {
    if (!mounted) return;

    // 如果上一个AI流未正确结束，先尝试固化它
    if (_isStreamingAiMessage && state.interviewerText.isNotEmpty) {
      _finalizeStreamingAiMessage();
    }
    // 添加一个空的AI消息作为占位符
    _addMessage(MessageModel(text: "", sender: MessageSender.interviewer, timestamp: DateTime.now()));
    _isStreamingAiMessage = true;
    state = state.copyWith(interviewerText: ""); // 清空，准备接收新内容
    KLog.i("InterviewDetailNotifier", "AI开始流式输出，添加空消息，_isStreamingAiMessage = true");
  }

  // AI 正在流式输出，更新文本 (isAISpeedSay=true, definite=false/true)
  void updateAiStreamingText(String newText) {
    if (!mounted) return;
    state = state.copyWith(interviewerText: newText);
  }

  // AI 一句话流式输出完毕 (definite=true 时调用)
  void finalizeAiStreamingMessage() {
    if (!mounted) return;
    _finalizeStreamingAiMessage();
  }

  // 内部方法：固化当前流式AI消息
  void _finalizeStreamingAiMessage() {
    if (!mounted) return;

    if (_isStreamingAiMessage && state.interviewerText.isNotEmpty) {
      final currentMessages = List<MessageModel>.from(state.msgList);
      // 找到最后一条由面试官发送且内容为空的消息
      int lastEmptyInterviewerMsgIndex = currentMessages.lastIndexWhere(
        (m) => m.sender == MessageSender.interviewer && m.text.isEmpty,
      );

      if (lastEmptyInterviewerMsgIndex != -1) {
        currentMessages[lastEmptyInterviewerMsgIndex] = MessageModel(
          text: state.interviewerText, // 保存完整文本
          sender: MessageSender.interviewer,
          timestamp: currentMessages[lastEmptyInterviewerMsgIndex].timestamp,
        );
        state = state.copyWith(
          msgList: currentMessages,
          interviewerText: "", // 清空流式文本
        );
        KLog.i("InterviewDetailNotifier", "AI流式消息已固化: ${currentMessages[lastEmptyInterviewerMsgIndex].text}");
      } else {
        KLog.w("InterviewDetailNotifier", "尝试固化AI消息，但未找到空的AI消息条目。当前 interviewerText: ${state.interviewerText}");
        // 即使没找到，也清空，避免污染
        state = state.copyWith(interviewerText: "");
      }
    } else if (_isStreamingAiMessage && state.interviewerText.isEmpty) {
      // AI开始流了，但没内容就结束了，可能需要移除那个空消息，或者保留为空。
      // 为了简单，这里只清空 interviewerText。如果需要移除空消息，逻辑会更复杂。
      KLog.i("InterviewDetailNotifier", "AI流式消息结束，但interviewerText为空。");
      state = state.copyWith(interviewerText: "");
    }
    _isStreamingAiMessage = false; // 标记流式结束
  }

  void setAiDefiniteState(bool definite) {
    if (state.definite != definite) {
      state = state.copyWith(definite: definite);
    }
  }

  // 更新UI相关的AI说话状态 (isAISpeedSay 对应的值)
  void setAiSpeakingState(bool isSpeaking) {
    if (state.isAISpeedSay != isSpeaking) {
      state = state.copyWith(isAISpeedSay: isSpeaking);
    }
    // 如果AI停止说话 (isSpeaking变为false)，且之前在流式输出，则固化消息
    if (!isSpeaking && _isStreamingAiMessage) {
      KLog.i("InterviewDetailNotifier", "AI说话状态变为false，固化可能未完成的流式消息。");
      _finalizeStreamingAiMessage();
    }
  }

  void updateAnswerBtnVisible(bool visible) {
    if (state.isShowAnswerBtn != visible) {
      state = state.copyWith(isShowAnswerBtn: visible);
    }
  }

  void updateBottomBarVisible(bool visible) {
    if (state.isShowBottomBar != visible) {
      state = state.copyWith(isShowBottomBar: visible);
    }
  }

  void updateCandidateTextText(String text) {
    if (!mounted) return;
    // 当用户开始输入时，如果AI正在说话，应该停止AI的流并固化
    if (text.isNotEmpty && _isStreamingAiMessage) {
      _finalizeStreamingAiMessage();
      KLog.i("InterviewDetailNotifier", "用户开始输入，中断并固化AI消息");
    }
    state = state.copyWith(candidateText: text);
    if (text.isNotEmpty && !state.isShowAnswerBtn) {
      state = state.copyWith(isShowAnswerBtn: true);
    }
  }

  void clearCandidateText() {
    if (!mounted) return;
    state = state.copyWith(candidateText: "");
  }

  // 辅助getter，外部判断是否需要调用startAiStreaming
  // (但更好的做法是外部逻辑自己维护 _aiJustFinishedSpeaking 这种状态)
  bool get isCurrentlyStreamingAi => _isStreamingAiMessage;
}

enum LottieState { idle, start, speaking, end }

class LottieAnimationState {
  final LottieState currentState;
  final bool isLooping;

  LottieAnimationState({required this.currentState, this.isLooping = true});

  String get assetPath {
    switch (currentState) {
      case LottieState.idle:
        return 'assets/json/talk_off.json';
      case LottieState.start:
        return 'assets/json/talk_start.json';
      case LottieState.speaking:
        return 'assets/json/talk_ing.json';
      case LottieState.end:
        return 'assets/json/talk_end.json';
    }
  }

  LottieAnimationState copyWith({LottieState? currentState, bool? isLooping}) {
    return LottieAnimationState(
      currentState: currentState ?? this.currentState,
      isLooping: isLooping ?? this.isLooping,
    );
  }
}

final lottieAnimationProvider = StateNotifierProvider.autoDispose<LottieAnimationNotifier, LottieAnimationState>((ref) {
  return LottieAnimationNotifier();
});

class LottieAnimationNotifier extends StateNotifier<LottieAnimationState> {
  LottieAnimationNotifier() : super(LottieAnimationState(currentState: LottieState.idle, isLooping: true));

  void setAnimation(LottieState newState, {required bool loop, Duration? duration}) {
    state = state.copyWith(currentState: newState, isLooping: loop);
    if (!loop && duration != null) {
      Future.delayed(duration, () {
        if (newState == LottieState.start) {
          state = state.copyWith(currentState: LottieState.speaking, isLooping: true);
        } else if (newState == LottieState.end) {
          state = state.copyWith(currentState: LottieState.idle, isLooping: true);
        }
      });
    }
  }
}
